import { useCallback, useEffect, useState } from 'react';
import { queryStringParse } from '@inbiz/utils';
import { TextWidget } from '@inbiz/react';
import { getDetail, getNewsList as getNewsListData } from '../../../service';
import { routerPrefix } from 'InbizConfig';
import { useEvents } from '@inbiz/utils';

const NewsDetail = (props: any) => {
  const prefixCls = 'inbiz-News-detail-wrapper';
  const { detail, newsKey } = props;
  const params = queryStringParse();
  const fixNewKey = Array.isArray(newsKey) ? newsKey :newsKey? [newsKey]:[];
  const [detailInfo, setDetail] = useState<News.NewsItem>();
  const [otherNewsList, setOtherNewsList] = useState<Array<News.NewsItem>>([]);
  const [configEvents] = useEvents(props.callBackEvents, props.emit)
  
  const getNewsList = useCallback(async (params: object) => {
    const newParams = (await configEvents.current?.onParams?.(params)) || params;
    const data = await (configEvents.current?.onRequest || getNewsListData)(newParams as any)
    return await configEvents.current?.onData?.(data) || data
  }, []);
  
  const getDetailInfo = () => {
    const { newsId } = params;
    if (!newsId) return;
    getDetail({ id: newsId }).then((res: News.NewsItem) => {
      setDetail(res);
    });
  };
  
  const getOtherNewsList = async () => {
    const { cateId, newsId } = params;
    const res: News.NewsList = await getNewsList({
      categoryId: cateId,
      pageIndex: 1,
      pageSize: 6,
      showNew: true,
      numNew: 10,
    });
    let arr: any = res?.ContentList || [];
    arr = arr.filter((item: any) => item.ID !== newsId).slice(0, 5);
    setOtherNewsList(arr);
  };

  const jumpToDetail = (record: any) => {
    const { ID, ContentUrl,ContentCategory } = record;
    if (!!ContentUrl) {
      window.open(ContentUrl);
      return;
    }
    if (!detail) return;
    const { origin, pathname, hash, search } = window.location;
    const { cateId } = params;
    const [name] = detail.split(',');
    window.open(
      `${origin}${pathname}${search}#${routerPrefix}${name}?newsId=${ID}&cateId=${ContentCategory}`,
    );
  };

  useEffect(() => {
    getDetailInfo();
  }, []);

  useEffect(() => {
    getOtherNewsList();
  }, [fixNewKey?.length]);

  return (
    <div className={prefixCls}>
      <div className={`${prefixCls}-box`}>
        <div className={`${prefixCls}-main`}>
          <div className={`${prefixCls}-main-title`}>{detailInfo?.Title}</div>
          <div className={`${prefixCls}-main-summary`}>
            <TextWidget>News.tips.abstract</TextWidget>：
            <span dangerouslySetInnerHTML={{ __html: detailInfo?.Summary || '' }}></span>
          </div>
          <div className={`${prefixCls}-main-source`}>
            <span>
              <TextWidget>News.tips.category</TextWidget>：{detailInfo?.Creator}&nbsp;&nbsp;
            </span>
            <span>
              <TextWidget>News.tips.laiyuan</TextWidget>：{detailInfo?.ContentCategoryName}
              &nbsp;|&nbsp;
              {detailInfo?.CreateTime}
            </span>
          </div>
          <div
            className={`${prefixCls}-main-content`}
            dangerouslySetInnerHTML={{ __html: detailInfo?.Content || '' }}
          ></div>
        </div>
        <div className={`${prefixCls}-more`}>
          <div className={`${prefixCls}-more-title`}>
            <TextWidget>News.tips.more_new_notice</TextWidget>
          </div>
          <ul>
            {otherNewsList.map((i) => (
              <li
                className="text-ellipsis"
                key={i.ID}
                title={i.Title}
                onClick={() => jumpToDetail(i)}
              >
                {i.Title}
              </li>
            ))}
          </ul>
        </div>
      </div>
    </div>
  );
};

export default NewsDetail;
